#!/bin/bash

: '

生成证书
cd /opt/apps/alist
openssl req -newkey rsa:2048 -nodes -keyout example.key -x509 -days 365 -out example.crt

'

SWNAME=caddy
# SWVER=v2.9.0-beta.3

# 注意安装顺序，后装者依赖前装者
DEB_PATH1=./downloads/${SWNAME}.deb

DIR_DESKTOP_FILES=/usr/share/applications
DSK_FILE=${SWNAME}.desktop
DSK_PATH=${DIR_DESKTOP_FILES}/${DSK_FILE}

action=$1
if [ "$action" == "" ]; then action=安装; fi

. ./scripts/common.sh

function sw_download() {
	tmpdns=`cd /exbin && droidexec ./vm_getHostByName.sh ${GITHUB_PROXY_HOST}`
	exit_if_fail $? "DNS解析失败"
	echo "$tmpdns" >> /etc/hosts

	case "${CURRENT_VM_ARCH}" in
		"arm64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/caddyserver/caddy/releases/download/v2.9.0-beta.3/caddy_2.9.0-beta.3_linux_arm64.deb"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		"amd64")
			swUrl="${GITHUB_PROXY_HTTP}https://github.com/caddyserver/caddy/releases/download/v2.9.0-beta.3/caddy_2.9.0-beta.3_linux_amd64.deb"
			download_file2 "${DEB_PATH1}" "${swUrl}"
			exit_if_fail $? "下载失败，网址：${swUrl}"
		;;
		*) exit_unsupport ;;
	esac
}

function sw_install() {

	sudo apt-get install -y ${ZZSWMGR_MAIN_DIR}/${DEB_PATH1}
	exit_if_fail $? "安装失败"

    sed -i 's#80#2019#g'  /etc/caddy/Caddyfile
}

function sw_create_desktop_file() {
	echo "正在生成桌面文件"

	tmpfile=${DSK_FILE}
	cat <<- EOF > ${tmpfile}
	[Desktop Entry]
	Name=启动${SWNAME}
	Exec=caddy run -c /etc/caddy/Caddyfile
	Type=Application
	Terminal=true
	EOF
	cp2desktop ${tmpfile}

	gxmessage -title "提示"     $'\n安装完成\n\n'  -center
}

if [ "${action}" == "卸载" ]; then
	# echo "暂不支持卸载"
	# exit 1
	rm2desktop ${SWNAME}.desktop
	apt-get clean
else
	sw_download
	sw_install
	sw_create_desktop_file
fi

